package com.turman.math_learn
import android.content.Context
import android.webkit.MimeTypeMap
import fi.iki.elonen.NanoHTTPD
import java.io.IOException
import java.io.InputStream

class LocalWebServer(context: Context, port: Int) : NanoHTTPD(port) {
    private val context: Context = context

    override fun serve(session: IHTTPSession): Response {
        var uri = session.uri

        // 默认加载 index.html
        if (uri == "/") {
            uri = "/index.html"
        }

        // 去掉开头的 "/"（assets 路径不需要斜杠）
        val assetPath = if (uri.startsWith("/")) uri.substring(1) else uri

        return try {
            // 从 assets 读取文件
            val inputStream: InputStream = context.assets.open(assetPath)
            val mimeType = getMimeType(uri)
            newChunkedResponse(Response.Status.OK, mimeType, inputStream)
        } catch (e: IOException) {
            // 文件不存在，返回 404
            newFixedLengthResponse(Response.Status.NOT_FOUND, "text/plain", "404 Not Found: $uri")
        }
    }

    // 根据文件后缀获取 MIME 类型
    private fun getMimeType(uri: String): String {
        val extension = MimeTypeMap.getFileExtensionFromUrl(uri)
        return if (extension != null) {
            MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension) ?: "text/plain"
        } else {
            "text/plain"
        }
    }
}